/**
 * Created by luoqiming on 2016/12/8.
 */

//引入模块
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
    host: ['10.60.17.34:9200','10.60.17.33:9200']
    //log: 'trace'
});

var es = {
    searchKey : function (esIndex, searchkey, callback) {
        client.search({
            index: esIndex, //索引
            //scroll: '30s',      //保持屏幕滚动的30S
            //source: ['_id'], //来源
            q: searchkey
        }, function (error, response) {
            if (error) {
                console.error(error.message);
            } else {
                var hits = response.hits.hits;
                console.log('索引%s查询结果%s', esIndex, hits);
                var charObj = count_Es_id(hits);
                callback(charObj);
            }
        });
    },
    serachContent: function (esIndex, callback) {
        query_count_startTime(esIndex, callback);
    },
    count : function (esIndex, callback) {
        callback(allCount(esIndex));
    }
}

/**
 * 根据关键字统计
 * @param data
 * @returns {Array}
 */
function count_Es_id(data) {
    if (data.length > 0) {
        //排序
        data.sort(sort_Es)
        var array = new Array();
        console.log(JSON.stringify(data));

        //过滤掉不需要的字段
        for (var i = 0; i < data.length; i++) {
            var startTime = data[i]._source.doc.startTime;
            var id = data[i]._source.doc.id;
            var content = data[i]._source.doc.content;
            var obj = {id:id,startTime: startTime, content: content};
            array.push(obj);
        }
        console.log('过滤后的字段:')
        console.log(JSON.stringify(array));

        //第一步 步骤
        console.log("第一步时间差:", difference(array[0].startTime,array[1].startTime));
        console.log("第二步时间差:", difference(array[0].startTime,array[2].startTime));
        console.log("第三步时间差:", difference(array[2].startTime,array[3].startTime));
        console.log("第四步时间差:", difference(array[3].startTime,array[4].startTime));
        console.log("第五步时间差:", difference(array[4].startTime,array[5].startTime));

        var obj = new Array();
        obj.push({"countKey":"xd-to-ibmmq","count_value":difference(array[0].startTime,array[1].startTime)});
        obj.push({"countKey":"xd-to-rabbit","count_value":difference(array[0].startTime,array[2].startTime)});
        obj.push({"countKey":"rabbit-to-app","count_value":difference(array[2].startTime,array[3].startTime)});
        obj.push({"countKey":"app-search-mogodb","count_value":difference(array[3].startTime,array[4].startTime)});
        obj.push({"countKey":"app-save-mogodb","count_value":difference(array[4].startTime,array[5].startTime)});
        return obj;
    }
}

function query_all_es_id(esIndex) {
    client.search({
        index: esIndex, //索引
        body: {
            "size": 0,
            "aggs": {
                "resultCount": {
                    "terms": {
                        "field": "doc.id.keyword",
                        "size": 8000,
                        "order": {
                            "startTime": "asc"
                        }
                    },
                    "aggs": {
                        "startTime": {
                            "sum": {
                                "field": "doc.startTime"
                            }
                        }
                    }
                }
            }
        }
    },function (error, response) {

    });
}

/**
 * 根据关键字统计数量
 * @param esIndex
 * @param condition
 */
function count_Es_number(esIndex, callback) {
    client.search({
        index: esIndex,
        //q:condition,
        body:{
            "size": 0,
            "query": {
                "bool": {
                    "must": [
                        {
                            "query_string": {
                                "query": "*",
                                "analyze_wildcard": true
                            }
                        },
                        {
                            "range": {
                                "@timestamp": {
                                    "gte": 1481644800000,
                                    "lte": 1481731199999,
                                    "format": "epoch_millis"
                                }
                            }
                        }
                    ],
                    "must_not": []
                }
            },
            "aggs": {
                "groupId": {
                    "terms": {
                        "field": "doc.id.keyword",
                        "size": 1000,
                        "order": {
                            "_term": "desc"
                        }
                    }
                }
            }
        }
    }, function (error, response) {
        callback(response.aggregations.groupId.buckets);
    });
}

/**
 * 根据ID查询
 * @param esIndex
 * @param key
 */
function searchId(esIndex, key) {
    console.log("索引:%s, 关键词:%s", esIndex, key);
    client.search({
        index: esIndex, //索引
        //scroll: '30s',      //保持屏幕滚动的30S
        //source: ['_id'], //来源
        body: {
            "query" : {
                "term" : { "doc.id.keyword" : key }
            },
            "sort": [{"doc.startTime":{"order":"asc"}}]
        }

    }, function (error, response) {
        if (error) {
            console.error(error.message);
        } else {
            var hits = response.hits.hits;
            console.log('索引%s查询结果%s', esIndex, hits);
            var charObj = count_Es_id(hits);
            query_array.push(charObj);
            console.log("全部数据:");

            console.log(JSON.stringify(query_array));
        }
    });
}
var query_array = new Array();
function allCount(esIndex) {

    count_Es_number(esIndex,function (data) {
        console.log("data_id_length:", data.length);
        for (var i = 0; i < data.length; i++) {
            //var key = 'doc.id:"'+ data[i].key +'"';
            searchId(esIndex, data[i].key);
        }
    });

}



function query_count_startTime(esIndex, callback) {
    client.search({
        index: esIndex, //索引
        //q:condition,
        body: {
            "query": {
                "bool": {
                    "must": [
                        {
                            "query_string": {
                                "analyze_wildcard": true,
                                "query": "doc.content:*"
                            }
                        }

                    ],
                    "must_not": []
                }
            },
            "size": 0,
            "aggs": {
                "resultCount": {
                    "terms": {
                        "field": "doc.content.keyword",
                        "size": 8000,
                        "order": {
                            "startTime": "asc"
                        }
                    },
                    "aggs": {
                        "startTime": {
                            "sum": {
                                "field": "doc.startTime"
                            }
                        }
                    }
                }
            }
        }
    }, function (error, response) {
        if (error) {
            console.error(error.message);
        } else {
            var resultCount = response.aggregations.resultCount;
            console.log("统计查询:",JSON.stringify(resultCount.buckets));
            callback(formatArray(resultCount.buckets));
        }
    });
}


function sliceArray(data) {
    var array = new Array();
    if (data.length > 0) {
        var start = 0;
        var end = 100;
        for (var i = 0 ; i < 180; i++) {
            array.push(data.slice(start, end))
            start = end+1;
        }
    }
    return array;
}


function aginArray(array, esIndex) {
    if (array.length > 0) {
        client.search({
            index: esIndex,
            body: {
                query: {
                    match_phrase: {
                        "doc.id": ''
                    }
                },
            }
        });
    }
}

/**
 * 排序
 * @param a
 * @param b
 * @returns {number}
 */
function sort_Es(a, b) {
    return a._source.doc.startTime-b._source.doc.startTime;
}

/**
 * 数值差
 * @param val_1
 * @param val_2
 * @returns {number}
 */
function difference(val_1, val_2) {
    return val_2 - val_1;
}

function formatArray(data) {
    var obj = new Array();
    if (data != null && data.length > 0) {
        obj.push({"countKey":"xd-to-ibmmq","count_value":(difference(data[0].startTime.value,data[1].startTime.value))});
        obj.push({"countKey":"xd-to-rabbit","count_value":(difference(data[0].startTime.value,data[2].startTime.value))});
        obj.push({"countKey":"rabbit-to-app","count_value":(difference(data[2].startTime.value,data[3].startTime.value))});
        obj.push({"countKey":"app-search-mogodb","count_value":(difference(data[3].startTime.value,data[4].startTime.value))});
        obj.push({"countKey":"app-save-mogodb","count_value":(difference(data[4].startTime.value,data[5].startTime.value))});
    }
    console.log(JSON.stringify(obj));
    /*var countValue = 0;
    for (var i = 0; i < data.length; i ++) {
        countValue += data[i].count_value;
    }*/
    //countValue = (countValue/1000)/data[0].doc_count;
    //console.log("平均时间:", countValue);
    return obj;
}

module.exports = es;


